package com.ys.service.finance.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ys.entity.sys.TbCompanyInfo;
import com.ys.enume.base.TransactionTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.business.TbPlatformServicePayAccount;
import com.ys.entity.finance.TcwPartnerWbAccount;
import com.ys.entity.finance.TcwWanliOtherPayment;
import com.ys.entity.finance.TcwWanliOtherPaymentItem;
import com.ys.entity.flow.YspModel;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.hr.ThrTransparencyProgramItem;
import com.ys.entity.hr.ThrVatApplyDetail;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.finance.PaymentEnum;
import com.ys.enume.finance.TcwWanliOtherPaymentEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.finance.FinanceMapper;
import com.ys.mapper.finance.TcwWanliOtherPaymentItemMapper;
import com.ys.mapper.finance.TcwWanliOtherPaymentMapper;
import com.ys.mapper.hr.ThrTransparencyProgramItemMapper;
import com.ys.mapper.hr.ThrVatApplyDetailMapper;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.finance.TcwAccountCountForWanliService;
import com.ys.service.finance.TcwWanliOtherPaymentService;
import com.ys.service.flow.YspTaskService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;

@Service("tcwWanliOtherPaymentService")
public class TcwWanliOtherPaymentServiceImpl implements TcwWanliOtherPaymentService {

	@Autowired
	private FinanceMapper financeMapper;
	@Autowired
	private TcwWanliOtherPaymentMapper tcwWanliOtherPaymentMapper;
	@Autowired
	private TcwWanliOtherPaymentItemMapper tcwWanliOtherPaymentItemMapper;
	@Autowired
	private ThrVatApplyDetailMapper thrVatApplyDetailMapper;
	@Autowired
	private ThrTransparencyProgramItemMapper thrTransparencyProgramItemMapper;
	
	
	@Autowired
	private YspTaskService yspTaskService;
	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;
    @Autowired
    private TcwAccountCountForWanliService tcwAccountCountForWorldFirstService;
    
	/**
	 * 新增
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional
	public R add(String bid, String depositPlatformCode, Integer payType, String countryCode, String currencyCodeOut, BigDecimal exchangeRate, String remark, BigDecimal amountTotalLocal, BigDecimal amountTotalCny, String detailArr, Long menuId) throws Exception {

		if (bid == null || bid.length() == 0) {
			return R.error("单号不能为空");
		} else if(new TcwWanliOtherPayment().setBid(bid).count() > 0) {
			return R.error("单号已存在");
		}
		
		if (depositPlatformCode == null || depositPlatformCode.length() == 0) {
			return R.error("收款平台账号编码不能为空");
		}
		
		if (payType == null) {
			return R.error("付款类型不能为空");
		}
		
		if (currencyCodeOut == null || currencyCodeOut.length() == 0) {
			return R.error("付款币种不能为空");
		}
		
		if (countryCode == null || countryCode.length() == 0) {
			return R.error("国家编码不能为空");
		}
		
		if (exchangeRate == null ) {
			return R.error("计算汇率不能为空");
		}
		
		/*
		 *  根据付款类型验证详情
		 *  1、付款金额不能为空
		 *  2、交易类型不能为空
		 *  3、当类型为透明计划或者VAT申报时，相关ID不能为空
		 *  4、当类型为其它时，运营公司编码，付款账户名称、付款银行名称、付款ABA，付款银行账号，银行国际代码不能为空
		 */
		JSONArray detailJA = JSON.parseArray(detailArr);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			
			BigDecimal amount = detailJO.getBigDecimal("amount");
			if (amount == null) {
				return R.error("付款金额不能为空");
			}
			String vjylx = detailJO.getString("vjylx");
			if (vjylx == null || vjylx.length() == 0) {
				return R.error("交易类型不能为空");
			}
			String currencyCode = detailJO.getString("currencyCode");
			if (currencyCode == null || currencyCode.length() == 0) {
				return R.error("币种不能为空");
			} else if (!currencyCodeOut.equals(currencyCode)) {
				return R.error("币种不一致");
			}
			
			Long relativeId = detailJO.getLong("relativeId");
			if (relativeId == null) {
				return R.error("相关ID不能为空");
			}
			
			if (payType == TcwWanliOtherPaymentEnum.PayType.OTHER.value) {
				
				String vgsbm = detailJO.getString("vgsbm");
				if (vgsbm == null || vgsbm.length() == 0) {
					return R.error("公司编码不能为空");
				}
				String vyhzhmc = detailJO.getString("vyhzhmc");
				if (vyhzhmc == null || vyhzhmc.length() == 0) {
					return R.error("付款账户名称不能为空");
				}
				String vkhh = detailJO.getString("vkhh");
				if (vkhh == null || vkhh.length() == 0) {
					return R.error("付款银行名称不能为空");
				}
				String vaba = detailJO.getString("vaba");
				if (vaba == null || vaba.length() == 0) {
					return R.error("付款ABA不能为空");
				}
				String vyhzh = detailJO.getString("vyhzh");
				if (vyhzh == null || vyhzh.length() == 0) {
					return R.error("付款银行账号不能为空");
				}
				String swiftCode = detailJO.getString("swiftCode");
				if (swiftCode == null || swiftCode.length() == 0) {
					return R.error("银行国际代码不能为空");
				}
			}
		}
		
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();
		
		TcwWanliOtherPayment entity = null;
		{
			Integer effectStock = FlowEnum.EffectStock.NOT_EFFECT.value;
			Long createChangeId = tsUserChange.getId();
			Integer stateRunning = TcwWanliOtherPaymentEnum.StateRunning.NOT.value;
			String annexFile = "0个附件";
			entity = TcwWanliOtherPayment.tcwWanliOtherPayment(bid, effectStock, createChangeId, depositPlatformCode, payType, countryCode, currencyCodeOut, exchangeRate, remark, amountTotalLocal, amountTotalCny, annexFile, stateRunning, 1);
			tcwWanliOtherPaymentMapper.insert(entity);
		}
		
		// 添加万里汇外币付款单明细
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			
			String pbid = bid;
			Long relativeId = detailJO.getLong("relativeId");
			String vgsbm = detailJO.getString("vgsbm");
			BigDecimal amount = detailJO.getBigDecimal("amount");
			BigDecimal fee = detailJO.getBigDecimal("fee");
			String currencyCode = detailJO.getString("currencyCode");
			String vjylx = detailJO.getString("vjylx");
			String vyhzhmc = detailJO.getString("vyhzhmc");
			String vkhh = detailJO.getString("vkhh");
			String vaba = detailJO.getString("vaba");
			String vyhzh = detailJO.getString("vyhzh");
			String swiftCode = detailJO.getString("swiftCode");
			Integer statePay = detailJO.getInteger("statePay");
			statePay = statePay == null ? PaymentEnum.StatePay.INIT.value : statePay;
			String remark2 = detailJO.getString("remark");
			TcwWanliOtherPaymentItem tcwWanliOtherPaymentItem = TcwWanliOtherPaymentItem.tcwWanliOtherPaymentItem(
					pbid, relativeId, vgsbm, amount, fee, currencyCode, vjylx, vyhzhmc, vkhh, vaba, vyhzh, swiftCode, remark2, statePay, 1);
			tcwWanliOtherPaymentItemMapper.insert(tcwWanliOtherPaymentItem);
		}

		TbCompanyInfo tbCompanyInfo = new TbCompanyInfo()
				.addLeftJoin("TCW_DepositPlatform B ON B.CompanyVid = A.Vid")
				.where("B.Code = '"+depositPlatformCode+"'")
				.queryFirst();
		String companyName = "";
		if(tbCompanyInfo!=null) companyName = tbCompanyInfo.getVname();
		/*
		 * 流程初始化
		 */
		YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, bid, createUserId);
			yspTaskService.setOtherParams(entity.getBid(),entity.getRemark(),companyName);
		}
		return R.ok(AddDto.gotoEdit("/web/finance/tcwWanliOtherPayment/toFlow?bid=" + bid));
	}
	
	@Override
	@Transactional
	public R edit(String bid, String depositPlatformCode, Integer payType, String countryCode, String currencyCodeOut, BigDecimal exchangeRate, String remark, BigDecimal amountTotalLocal, BigDecimal amountTotalCny, String detailArr, Long menuId) throws Exception {
		
		if (exchangeRate == null) {
			return R.error("计算汇率不能为空");
		}
		
		Integer stateFlow = yspTaskService.flowState(bid);
		if (stateFlow == YsProcInstEnum.StateFlow.FINISH.value) {
			return R.error("已流转结束，无法修改");
		}
		
		/*
		 *  根据付款类型验证详情
		 *  1、付款金额不能为空
		 *  2、交易类型不能为空
		 *  3、当类型为透明计划或者VAT申报时，相关ID不能为空
		 *  4、当类型为其它时，运营公司编码，付款账户名称、付款银行名称、付款ABA，付款银行账号，银行国际代码不能为空
		 */
		JSONArray detailJA = JSON.parseArray(detailArr);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			
			BigDecimal amount = detailJO.getBigDecimal("amount");
			if (amount == null) {
				return R.error("付款金额不能为空");
			}
			String vjylx = detailJO.getString("vjylx");
			if (vjylx == null || vjylx.length() == 0) {
				return R.error("交易类型不能为空");
			}
			String currencyCode = detailJO.getString("currencyCode");
			if (currencyCode == null || currencyCode.length() == 0) {
				return R.error("币种不能为空");
			} else if (!currencyCodeOut.equals(currencyCode)) {
				return R.error("币种不一致");
			}
			
			Long relativeId = detailJO.getLong("relativeId");
			if (relativeId == null) {
				return R.error("相关ID不能为空");
			}
			
			if (payType == TcwWanliOtherPaymentEnum.PayType.OTHER.value) {
				
				String vgsbm = detailJO.getString("vgsbm");
				if (vgsbm == null || vgsbm.length() == 0) {
					return R.error("公司编码不能为空");
				}
				String vyhzhmc = detailJO.getString("vyhzhmc");
				if (vyhzhmc == null || vyhzhmc.length() == 0) {
					return R.error("付款账户名称不能为空");
				}
				String vkhh = detailJO.getString("vkhh");
				if (vkhh == null || vkhh.length() == 0) {
					return R.error("付款银行名称不能为空");
				}
				String vaba = detailJO.getString("vaba");
				if (vaba == null || vaba.length() == 0) {
					return R.error("付款ABA不能为空");
				}
				String vyhzh = detailJO.getString("vyhzh");
				if (vyhzh == null || vyhzh.length() == 0) {
					return R.error("付款银行账号不能为空");
				}
				String swiftCode = detailJO.getString("swiftCode");
				if (swiftCode == null || swiftCode.length() == 0) {
					return R.error("银行国际代码不能为空");
				}
			}
		}
		
		// 更新主表数据
		TcwWanliOtherPayment tcwWanliOtherPayment = new TcwWanliOtherPayment().setBid(bid).queryFirst();
		tcwWanliOtherPayment
			.setDepositPlatformCode(depositPlatformCode)
			.setPayType(payType)
			.setCountryCode(countryCode)
			.setCurrencyCodeOut(currencyCodeOut)
			.setExchangeRate(exchangeRate)
			.setRemark(remark)
			.setAmountTotalLocal(amountTotalLocal)
			.setAmountTotalCny(amountTotalCny);
		tcwWanliOtherPaymentMapper.update(tcwWanliOtherPayment);
		
		// 删除旧的详情数据
		financeMapper.deleteTcwWanliOtherPaymentByPbid(bid);
		
		// 添加万里汇外币付款单明细
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			
			String pbid = bid;
			Long relativeId = detailJO.getLong("relativeId");
			String vgsbm = detailJO.getString("vgsbm");
			BigDecimal amount = detailJO.getBigDecimal("amount");
			BigDecimal fee = detailJO.getBigDecimal("fee");
			String currencyCode = detailJO.getString("currencyCode");
			String vjylx = detailJO.getString("vjylx");
			String vyhzhmc = detailJO.getString("vyhzhmc");
			String vkhh = detailJO.getString("vkhh");
			String vaba = detailJO.getString("vaba");
			String vyhzh = detailJO.getString("vyhzh");
			String swiftCode = detailJO.getString("swiftCode");
			Integer statePay = detailJO.getInteger("statePay");
			String remark2 = detailJO.getString("remark");
			TcwWanliOtherPaymentItem tcwWanliOtherPaymentItem = TcwWanliOtherPaymentItem.tcwWanliOtherPaymentItem(
					pbid, relativeId, vgsbm, amount, fee, currencyCode, vjylx, vyhzhmc, vkhh, vaba, vyhzh, swiftCode, remark2, statePay, 1);
			tcwWanliOtherPaymentItemMapper.insert(tcwWanliOtherPaymentItem);
		}


		TbCompanyInfo tbCompanyInfo = new TbCompanyInfo()
				.addLeftJoin("TCW_DepositPlatform B ON B.CompanyVid = A.Vid")
				.where("B.Code = '"+depositPlatformCode+"'")
				.queryFirst();
		String companyName = "";
		if(tbCompanyInfo!=null) companyName = tbCompanyInfo.getVname();
		yspTaskService.setOtherParams(tcwWanliOtherPayment.getBid(),tcwWanliOtherPayment.getRemark(),companyName);

		return R.ok(EditDto.reloadPage("/web/hr/tcwWanliOtherPayment/toFlow?bid=" + bid));
	}

	@Override
	@Transactional
	public R deleteTrue(Long id) throws Exception {
		if (id == null) {
			return R.error("ID不能为空");
		}
		
		TcwWanliOtherPayment entity = new TcwWanliOtherPayment().setId(id).queryFirst();
		
		Integer stateFlow = yspTaskService.flowState(entity.getBid());
		if (stateFlow != YsProcInstEnum.StateFlow.INIT.value) {
			return R.error("非制单状态，无法修改");
		}
		
		// 验证是否制单人
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();
		
		if (!tsUserChange.getUserId().equals(loginUserId)) {
			return R.error("非制单人，无法删除");
		}
		
		// 删除主数据
		tcwWanliOtherPaymentMapper.deleteTrue(id);
		
		// 删除子数据
		List<TcwWanliOtherPaymentItem> listDetail = new TcwWanliOtherPaymentItem().setPbid(entity.getBid()).queryList();
		for(TcwWanliOtherPaymentItem detail : listDetail) {
			tcwWanliOtherPaymentItemMapper.deleteTrue(detail.getId());
		}
		
		yspTaskService.flowDelete(entity.getBid(), loginUserId);
		return R.ok();
	}

	@Override
	@Transactional
	public R flowPass(String bid, String loginUserId) throws Exception {
		
		// 若流程是初始化状态，需验证数据的可用性
		YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
		TcwWanliOtherPayment tcwWanliOtherPayment = null;
		if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
			tcwWanliOtherPayment = new TcwWanliOtherPayment().setBid(bid).queryFirst();
			
			if (tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.TOUMING.value || tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.VAT.value) {
				List<TcwWanliOtherPaymentItem> listTcwWanliOtherPaymentItem = new TcwWanliOtherPaymentItem().setPbid(bid).queryList();
				for(TcwWanliOtherPaymentItem item : listTcwWanliOtherPaymentItem) {
					if (tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.TOUMING.value) {
						if (new ThrTransparencyProgramItem().setId(item.getRelativeId()).setStatePay(PaymentEnum.StatePay.INIT.value).count() != 1) {
							return R.error("透明计划单据非待支付状态，无法操作");
						}
					} else if (tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.VAT.value) {
						if (new ThrVatApplyDetail().setId(item.getRelativeId()).setStatePay(PaymentEnum.StatePay.INIT.value).count() != 1) {
							return R.error("透明计划单据非待支付状态，无法操作");
						}
					}
				}
			}
		}
		
		try {
			Flow f = yspTaskService.flowPass(bid, loginUserId);
			if (f.getCode() == Flow.Code.FAILED.value) {
				return R.error(f.getMsg());
			} else {
				if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
					
					if (tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.TOUMING.value || tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.VAT.value) {
						List<TcwWanliOtherPaymentItem> listTcwWanliOtherPaymentItem = new TcwWanliOtherPaymentItem().setPbid(bid).queryList();
						for(TcwWanliOtherPaymentItem item : listTcwWanliOtherPaymentItem) {
							if (tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.TOUMING.value) {
								ThrTransparencyProgramItem detail = new ThrTransparencyProgramItem().setId(item.getRelativeId()).queryFirst();
								detail.setStatePay(PaymentEnum.StatePay.PROCESS.value);
								thrTransparencyProgramItemMapper.update(detail);
							} else if (tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.VAT.value) {
								ThrVatApplyDetail detail = new ThrVatApplyDetail().setId(item.getRelativeId()).queryFirst();
								detail.setStatePay(PaymentEnum.StatePay.PROCESS.value);
								thrVatApplyDetailMapper.update(detail);
							}
						}
					}
				}
				
				if (f.getState() == Flow.State.FINISH.value) {
					flowFinish(bid);
				}
				return R.ok();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	@Override
	public R flowRefuse(String bid, String reason, String loginUserId) throws Exception {
		
		R r = yspTaskService.flowRefuse(bid, reason, loginUserId);
		
		if (r.getCode() == R.Code.SUCCESS.value) {
			// 若流程退回到初始化状态，解冻可用库存
			YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				TcwWanliOtherPayment tcwWanliOtherPayment = new TcwWanliOtherPayment().setBid(bid).queryFirst();
				
				if (tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.TOUMING.value || tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.VAT.value) {
					List<TcwWanliOtherPaymentItem> listTcwWanliOtherPaymentItem = new TcwWanliOtherPaymentItem().setPbid(bid).queryList();
					for(TcwWanliOtherPaymentItem item : listTcwWanliOtherPaymentItem) {
						if (tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.TOUMING.value) {
							ThrTransparencyProgramItem detail = new ThrTransparencyProgramItem().setId(item.getRelativeId()).queryFirst();
							detail.setStatePay(PaymentEnum.StatePay.INIT.value);
							thrTransparencyProgramItemMapper.update(detail);
						} else if (tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.VAT.value) {
							ThrVatApplyDetail detail = new ThrVatApplyDetail().setId(item.getRelativeId()).queryFirst();
							detail.setStatePay(PaymentEnum.StatePay.INIT.value);
							thrVatApplyDetailMapper.update(detail);
						}
					}
				}
			}
		}
		return r;
	}

	@Override
	@Transactional
	public void flowFinish(String bid) throws Exception {

		TcwWanliOtherPayment entity = new TcwWanliOtherPayment().setBid(bid).queryFirst();
		
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}


		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		tcwWanliOtherPaymentMapper.update(entity);
		
//		if (entity.getPayType() == TcwWanliOtherPaymentEnum.PayType.OTHER.value) {
//			List<TcwWanliOtherPaymentItem> listTcwWanliOtherPaymentItem = new TcwWanliOtherPaymentItem().setPbid(bid).queryList();
//			for(TcwWanliOtherPaymentItem tcwWanliOtherPaymentItem : listTcwWanliOtherPaymentItem) {
//				Long wanliOtherPaymentItemId = tcwWanliOtherPaymentItem.getId();
//				tcwWanliPayoutService.addPayOfOtherPayment(wanliOtherPaymentItemId);
//			}
//		}
	}

	@Override
	public R batchEditExchangeRate(BigDecimal exchangeRate, String detailArr) throws Exception {
		if(exchangeRate == null) {
			return R.error("费率不能为空");
		}
		JSONArray detailJA = JSON.parseArray(detailArr);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}
		List<String> listBid = new ArrayList<String>();
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			
			String bid = detailJO.getString("bid");
			if (bid == null || bid.length() == 0) {
				continue;
			}
			
			listBid.add(bid);
			
		}
		
		financeMapper.updateTcwWanliOtherPaymentExchangeRate(exchangeRate, listBid);
		
		financeMapper.updateTcwWanliOtherPaymentAmountCny(listBid);
		
		return R.ok();
	}

	@Override
	@Transactional
	public R generateRunning(String bid) throws Exception {
		
		if (bid == null || bid.length() == 0) {
			return R.error("单号不能为空");
		}

		TcwWanliOtherPayment entity = new TcwWanliOtherPayment().setBid(bid).queryFirst();
		if (entity.getEffectStock() != FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("尚未流转结束");
		} else if(entity.getStateRunning() != TcwWanliOtherPaymentEnum.StateRunning.NOT.value) {
			return R.error("状态不是未生成，无法操作");
		}
		
		entity.setStateRunning(TcwWanliOtherPaymentEnum.StateRunning.YES.value);
		tcwWanliOtherPaymentMapper.update(entity);

		List<TcwWanliOtherPaymentItem> listTcwWanliOtherPaymentItem = new TcwWanliOtherPaymentItem().setPbid(bid).queryList();
		{
			Date now = new Date();
			// 添加账户流水
			for(TcwWanliOtherPaymentItem detail : listTcwWanliOtherPaymentItem) {
				
				String vgsbmp = detail.getVyhzhmc();
				String vgsjcp = detail.getVyhzhmc();
				
				// 更新对应单据的支付状态
				if (entity.getPayType() == TcwWanliOtherPaymentEnum.PayType.TOUMING.value) {
					ThrTransparencyProgramItem sourceEntity = new ThrTransparencyProgramItem().setId(detail.getRelativeId()).queryFirst();
					sourceEntity.setStatePay(PaymentEnum.StatePay.SUCCESS.value);
					thrTransparencyProgramItemMapper.update(sourceEntity);
					
					TbPlatformServicePayAccount tbPlatformServicePayAccount = new TbPlatformServicePayAccount().setId(sourceEntity.getPtId()).queryFirst();
					vgsbmp = tbPlatformServicePayAccount.getBid();
					vgsjcp = tbPlatformServicePayAccount.getVyhzhmc();
				} else if (entity.getPayType() == TcwWanliOtherPaymentEnum.PayType.VAT.value) {
					ThrVatApplyDetail sourceEntity = new ThrVatApplyDetail().setId(detail.getRelativeId()).queryFirst();
					sourceEntity.setStatePay(PaymentEnum.StatePay.SUCCESS.value);
					thrVatApplyDetailMapper.update(sourceEntity);
					
					vgsbmp = sourceEntity.getVatNo();
					
				} else if (entity.getPayType() == TcwWanliOtherPaymentEnum.PayType.OTHER.value) {
					TcwPartnerWbAccount sourceEntity = new TcwPartnerWbAccount().setId(detail.getRelativeId()).queryFirst();

					vgsbmp = sourceEntity.getCode();
					vgsjcp = sourceEntity.getVyhzhmc();
					
				}

				String vgsbm = detail.getVgsbm();
				ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(vgsbm).queryFirst();
				
				// 添加运营公司账户流水
				String vgsjc = thrOperateCompanyApply.getVgsjc();
				String vjylx = detail.getVjylx();
				BigDecimal fje = detail.getAmount().add(detail.getFee()).multiply(entity.getExchangeRate()).negate();
				Date djysj = now;
				Date dshsj = now;
				String vbz = "万里汇外币付款单,单号：" + entity.getBid() + "," + entity.getRemark() + "," + detail.getRemark();
				Date writeTime = now;
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(vgsbm, vgsjc, vgsbmp, vgsjcp, vjylx, fje, djysj, dshsj, vbz, entity.getBid(),writeTime);


			}
		}





		for(TcwWanliOtherPaymentItem detail : listTcwWanliOtherPaymentItem) {
			ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(detail.getVgsbm()).queryFirst();
			boolean isCheckCapital = false;
			String depositPlatformCode = entity.getDepositPlatformCode();
			String exchangeRateCode = entity.getCurrencyCodeOut();
			Integer documentType = 5;
			BigDecimal accountCount = detail.getAmount().add(detail.getFee()).setScale(2, BigDecimal.ROUND_HALF_UP).negate();
			String remark = "运营公司简称：" + thrOperateCompanyApply.getVgsjc() + "，付款类型：" + TcwWanliOtherPaymentEnum.PayType.getName(entity.getPayType()) + "，单号：" + entity.getBid() + "，本单备注：" + entity.getRemark();
			tcwAccountCountForWorldFirstService.add(isCheckCapital, depositPlatformCode, exchangeRateCode, documentType,entity.getBid(), accountCount, remark);
		}
		
		return R.ok("操作成功");
	}

	@Override
	@Transactional
	public R flowInit(String bid, String reason, String loginUserId) throws Exception {
		TcwWanliOtherPayment tcwWanliOtherPayment = new TcwWanliOtherPayment().setBid(bid).queryFirst();
		if (tcwWanliOtherPayment.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("已流转完成，无法操作");
		}
		
		if (tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.TOUMING.value || tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.VAT.value) {
			List<TcwWanliOtherPaymentItem> listTcwWanliOtherPaymentItem = new TcwWanliOtherPaymentItem().setPbid(bid).queryList();
			for(TcwWanliOtherPaymentItem item : listTcwWanliOtherPaymentItem) {
				if (tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.TOUMING.value) {
					ThrTransparencyProgramItem detail = new ThrTransparencyProgramItem().setId(item.getRelativeId()).queryFirst();
					detail.setStatePay(PaymentEnum.StatePay.INIT.value);
					thrTransparencyProgramItemMapper.update(detail);
				} else if (tcwWanliOtherPayment.getPayType() == TcwWanliOtherPaymentEnum.PayType.VAT.value) {
					ThrVatApplyDetail detail = new ThrVatApplyDetail().setId(item.getRelativeId()).queryFirst();
					detail.setStatePay(PaymentEnum.StatePay.INIT.value);
					thrVatApplyDetailMapper.update(detail);
				}
			}
		}
		
		yspTaskService.flowInit(bid, reason, loginUserId);
		
		return R.ok();
	}

	//获取列表数据
	@Override
	@Transactional
	public Map<String,Object> getExtraParam(String bid) throws Exception{
		Map<String, Object> extraParam = new TcwWanliOtherPayment()

				.setBid(bid)

				.addLeftJoin("TCW_DepositPlatform B ON B.Code = A.DepositPlatformCode")
				.addField("B.PlatformName platformName")
				.addField("B.Code depositPlatformCode")
				.addField("B.Name depositPlatformName")

				.addLeftJoin("TB_CompanyInfo C ON C.Vid = B.CompanyVid")
				.addField("C.Vid companyVid")
				.addField("C.Vname companyVname")
				.addField("A.Remark premark")

				.addLeftJoin("YS_ProcInst D on D.Bid = A.Bid")
				.addField("CONVERT(VARCHAR(20), D.UpdateTime, 120) auditTime")

				.queryFirstMap();
		return extraParam;
	}
	//获取子列表数据
	@Override
	@Transactional
	public List<Map<String, Object>> getItemList( String bid) throws Exception{
		// 子列表配置信息
		List<Map<String, Object>> sonlist = new TcwWanliOtherPaymentItem()
				.addLeftJoin("TCW_WanliOtherPayment C ON C.Bid = A.Pbid")
				.setPbid(bid)
				.addLeftJoin("THR_OperateCompanyApply B on B.Vgsbm = A.Vgsbm")
				.addField("B.Vgsjc vgsjc")
				.addField("ROUND((A.Amount + A.Fee) * C.ExchangeRate, 2) amountCny")

				.queryMap();
		return sonlist;
	}


}
